/*
 * @Descripttion: 封装http
 * @version: 
 * @Author: 791984535@qq.com
 * @Date: 2020-05-05 14:40:07
 */ 
import {
  HOST,
  COOKIE,
  TOKEN
} from "../constances/server";

import wxp from '../utils/wxPromisify'

// 拼接链接
export function urlFix(url) {
  if (!url || url.startsWith('http')) return url;
  if (url.startsWith('/')) {
    return url.startsWith(HOST) ? url : `${HOST}${url}`;
  }
  return `${HOST}/${url}`;
}

/*
 *  通用requst
 *  @parmas
 *  method: 加载方式
 **/
export function request(method, url, params) {
  const cookie = wx.getStorageSync(COOKIE)
  const token = wx.getStorageSync(TOKEN) || undefined
  const header = {
    contentType: 'content-type:application/json;charset=utf-8', //跨域请求
  }
  if (cookie) {
    header.cookie = cookie
  }
  return wxp.request({
    method,
    header,
    url: urlFix(url),
    data: {
      ...params,
      token,
    }
  }).then(res => {
    if (!cookie) wx.setStorageSync('cookie', res.header['Set-Cookie']); //保存Cookie到Storage
    checkCode(res.data.code)
    return res.data
  }).catch(err => {
    console.log(err)
  })
}

/*
 *  通用get
 *  @parmas
 *  isShowLoading: 是否显示加载中
 **/
export function get(url, params, isShowLoading) {
  return request('GET', url, params)
  // return wx.re
}

/*
 *  通用post
 *  @parmas
 *  isShowLoading: 是否显示加载中
 **/
export function post(url, params, isShowLoading) {
  return request('POST', url, params)
}


//判断固定的状态码进行固定的操作
export function checkCode(code) {
  if (code === 401) {
    //用户未授权
    wx.showToast({
      duration: 2000,
      icon: 'none',
      title: '请先进行授权'
    })
    setTimeout(() => {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    }, 2000)
  }
}